var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var base64 = require('../../utils/Base64.js');
var topictitle = "";
var topicid = "";
var app = getApp();
var uid = '';
var uname = '';  //作者用户名
var wxAuthFail = true;
var inviteuid = 0;
var linkcode = '';

var detailMessage = '';

Page({
  data: {
    util: util,
    host: util.api_host,
    tc: 0,
    my_cion: 0,

    indicatorDots: true,
    autoplay: true,
    interval: 4000,
    duration: 600,
    swiper_w: 0,
    swiper_h: 0,

    video_w: 300,
    video_h: 165,

    detailShouhou: '',//售后保障

    data: {},
    likeuser: [],
    detailMessage: '',
    pinHistoryData: [], //拼单历史
    imgDomain: app.globalData.imgDomain,
    isFollow: false, //是否已关注
    isLiked: false, //是否已赞
    uid: '',  //当前登录用户Id
    token: '', //post请求时，当前登录用户token
    loginUname: '', //当前登录用户名
    commentMsg: '',
    replyid: 0, //当前被回复的评论id
    openid: '',
    topicid: 0,
    startTime: 0,
    hasShare: false,
    tuid: 0,
    firstImgUrl: '',
    canEdit: false,
    isShow: false,

    isIphone: false,

    isOnLoad: false,

    modalHidden: true,

    guigeData: [],
    selectGuige: '',

    gwc_count: 0,

    countValue: 1,

    curr: {
      goods_info: "curr",
      pinglun: "",
      shouhou: ""
    },

    contact_phone: '',

    commentList: [],
    colorSet: '',

    ghs_info: '',

    hide_commentview: true,
    pageIndex: "/pages/index/index",


    isIphone_x: false,
    actionBottom: 0,
    nav_bgColor: '#ffffff',

    huangou: 0
  },

  isLogin: false,
  userinfo: '',

  onLoad: function (data) {

    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", data);
    var tc = app.get_tc();
    var that = this;

    that.setData({
      tc: tc,
    });

    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", data.choosenum);
    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });

    var titlename = tc == 1 ? '詳情' : '详情';
    wx.setNavigationBarTitle({
      title: titlename,
    });
    this.getYunfeiSet();
    var that = this;


    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });
    that.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    })
    wx.getSystemInfo({
      success: function (res) {
        var isiPhone = (res.model.indexOf('iPhone') >= 0);
        // var height = res.windowWidth * 2 / 3;
        var height = res.windowWidth;
        var v_w = res.windowWidth;
        // v_w =  v_w - 25;
        var v_h = v_w * 4 / 7;
        that.setData({
          isIphone: isiPhone,
          swiper_w: res.windowWidth,
          swiper_h: height,
          video_w: v_w,
          video_h: v_h,
          goodsImgView_h: (res.windowWidth - 30) / 2,
          tc: tc
        });
      }
    })

    wx.getSystemInfo({
      success: function (res) {
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screen_h: res.windowHeight,
          actionBottom: isIphone_x ? 20 : 0
        });
      }
    });

    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    this.setData({
      gwc_count: gwc_datas.length
    });

    if (util.orgid == 18681) {
      var gwc_count = 0;
      gwc_datas.forEach(function (m, i) {
        gwc_count += m.buycount
      })
      this.setData({
        gwc_count: gwc_count
      });

    }

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck",
        "tc": that.data.tc
      },
      success: function (responseData) {
        console.log("是否显示：", responseData);
        app.isShow = responseData.data.isShow;
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    topicid = data.topicid || "";
    //是否是从 别人分享的 页面点进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    var pages = getCurrentPages();
    var curPageIndex = pages.length;
    //如果是分享进来 或者 当前栈下标 是 1 都认为是分享进来的  因为分享人可能没授权登录 无法分享邀请码
    var isShare = (inviteuid || curPageIndex <= 1);
    this.setData({
      hasShare: isShare,
      topicid: topicid,
      isOnLoad: true
    })
    that.setData({
      timeStamp: new Date().getTime()
    })
    //获取商品32位唯一id，用户商品三级分销
    linkcode = data.linkcode ? data.linkcode : '';

    app.getAllAbout('contact', function (res) {
      that.setData({
        contact_phone: res
      })
    });

    var showcomments = data.showcomments || "";
    console.log("showcomments", showcomments)
    that.setData({
      showcomments: showcomments
    });

  },

  onShow: function () {
    this.getLoginInfo();

    this.setData({
      isOnLoad: false,
    })

    var membercard = wx.getStorageSync('membercard');
    if (membercard) {
      this.isLogin = true;
    }

    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    if (util.orgid == 18681) {
      var gwc_count = 0;
      gwc_datas.forEach(function (m, i) {
        gwc_count += m.buycount
      })
      this.setData({
        gwc_count: gwc_count
      });

    }
  },

  //获取售后保障介绍
  getShouhouMsg: function () {
    var that = this;

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "shouhou",
        "uid": util.orgid
      },
      success: function (responseData) {
        console.log("售后保障：", responseData);
        that.setData({
          detailShouhou: responseData.data.msg,
        });
        /** 
        * WxParse.wxParse(bindName , type, data, target,imagePadding) 
        * 1.bindName绑定的数据名(必填) 
        * 2.type可以为html或者md(必填) 
        * 3.data为传入的具体数据(必填) 
        * 4.target为Page对象,一般为this(必填) 
        * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
        */
        WxParse.wxParse('detailShouhou', 'html', that.data.detailShouhou, that, 12);
      }
    });
  },

  changeContent: function (e) {
    var tag = e.currentTarget.dataset.tag;
    if (tag == 'gi') {
      this.setData({
        curr: {
          goods_info: "curr",
          pinglun: "",
          shouhou: ""
        }
      })
    } else if (tag == 'pl') {
      this.setData({
        curr: {
          goods_info: "",
          pinglun: "curr",
          shouhou: ""
        }
      })
    } else if (tag == 'sh') {
      this.setData({
        curr: {
          goods_info: "",
          pinglun: "",
          shouhou: "curr"
        }
      })
    }
  },

  load: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topicdetail",
      linkcode: linkcode,
      inviteuid: inviteuid,
      loginuid: that.data.uid ? that.data.uid : '',
      topicid: topicid,
      tc: that.data.tc
    };
    console.log("动态详情请求参数：", params);
    //动态详情
    util.api({
      data: params,
      success: function (responseData) {
        var data = responseData.data;
        console.log("啊啊啊啊啊详情：", data);

        if (uid == data.user.uid) {
          that.setData({
            canEdit: true
          })
        }
        if (util.orgid == 17784) {
          if (data.guige.indexOf("|") > 0) {
            var guigeTitleArray = data.guige.split("|");
            data.guigeTitleArray = guigeTitleArray;
            console.log("guigeTitleArray", guigeTitleArray)
          }
        }
        //获取规格商品
        that.getGuigeData(data.id);

        //供货商信息
        if (data.orgid) {
          app.GetUserInfo(data.orgid, function (res) {
            console.log("供货商信息：", res);
            that.setData({
              ghs_info: res
            })
          });
        }

        if (that.isLogin) {
          //处理折扣價
          console.log("商品信息开始时间：", data.starttime);
          var start2 = Date.parse(new Date(data.starttime));
          var end2 = Date.parse(new Date(data.endtime));
          var now = new Date().getTime();

          console.log("start2==" + start2 + "end2==" + end2 + "now===" + now);
          if (now > start2 && now < end2 && data.zhekou != "") {
            if (data.zhekou > 0 && data.zhekou < 1) {
              data.zhekouprice = data.memberprice * data.zhekou;
            } else if (data.zhekou >= 1 && data.zhekou <= data.memberprice) {
              data.zhekouprice = data.zhekou;
            } else {
              data.zhekouprice = data.memberprice;
            }
          }
        }
        //处理时间
        var date = new Date(data.dateline * 1000);
        data.formatDate = date.getFullYear() + "-" + (Number(date.getMonth()) + 1) + "-" + date.getDate();
        //处理语音
        if (data.audio) {
          data.formatAudio = JSON.parse(data.audio);
        }
        //处理视频
        if (data.video) {
          var videolinks = data.video.split(",");
          var len = videolinks.length;
          var tx_videolinks = [];
          for (var i = 0; i < len; i++) {
            if (videolinks[i].indexOf('v.qq.com') > 0) {
              tx_videolinks = tx_videolinks.concat(videolinks[i])
            }
          }
          len = tx_videolinks.length;
          var videoSrcs = new Array(len);
          var count = 0;
          for (var i = 0; i < len; i++) {
            app.getVideoSrcLink(i, tx_videolinks[i], function (url, index) {
              count++;
              if (url != -1) {
                videoSrcs[index] = url;
              }
              if (count >= len) {
                var videoSrcArr = [];
                for (var n = 0; n < len; n++) {
                  if (videoSrcs[n]) {
                    videoSrcArr = videoSrcArr.concat(videoSrcs[n]);
                  }
                }
                that.setData({
                  videolinkArray: videoSrcArr
                });
              }

            });
          }
        }
        var latitude = wx.getStorageSync('lat')
        var longitude = wx.getStorageSync('lon')
        var distanStr;
        if (latitude && longitude) {
          var distan = app.getDistance(latitude, longitude, data.lat, data.lon);
          if (distan > 1000) {
            distanStr = (distan / 1000).toFixed(2) + 'km';
          } else {
            distanStr = distan.toFixed(0) + 'm';
          }
          data.distanse = distanStr;

        }

        //处理message  
        detailMessage = data.message;
        // detailMessage = data.message.replace(/\n/g, '<br />');
        // console.log("detailMessage: ", detailMessage);

        that.setData({
          detailMessage: data.message,
        });
        /** 
        * WxParse.wxParse(bindName , type, data, target,imagePadding) 
        * 1.bindName绑定的数据名(必填) 
        * 2.type可以为html或者md(必填) 
        * 3.data为传入的具体数据(必填) 
        * 4.target为Page对象,一般为this(必填) 
        * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
        */
        WxParse.wxParse('detailMessage', 'html', detailMessage, that, 12);
        // data.message = data.message.replace(/&nbsp;/g, '');

        topictitle = data.topictitle;
        uname = data.user.username;

        var f_imgUrl = '';
        if (data.photoscbk && data.photoscbk.length > 0) {
          var firstImageInfo = data.photoscbk[0];
          if (firstImageInfo) {
            f_imgUrl = firstImageInfo.photo + "!120a";
          }
          let photoArr = data.photos.split(',');
          data.photoArr = photoArr;
        }
        console.log("第一张图片链接：", f_imgUrl);
        // 处理是否积分换购商品
        let huangou = 0;
        if ((!data.sellprice || data.sellprice == '0') && (!data.memberprice || data.memberprice == '0')) {
          console.log("是积分换购商品！！！！！！！");
          huangou = 1;
        }
        that.setData({
          data: data,
          likeuser: data.likeuser,
          isLiked: data.isLiked,
          tuid: data.postuid,
          firstImgUrl: f_imgUrl,
          huangou: huangou
        });
        //当前用户是否已关注作者
        that.isFollow(uid, data.postuid);
        //当前用户是否已赞该动态
        that.isLike(uid);
        wx.hideLoading();

        // 获取门店
        that.getghs();

        that.loadTopicCommentList(that.data.topicid, 1);
        that.markGoodWithRec();
        that.markGood();
      }
    });
    //拼单列表
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getgoodspin",
        goods_id: topicid,
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("历史拼单：", data);
        if (!data.msg) {
          var keys = [];
          for (var key in data) {
            keys.push(key);
          }
          var pinArray = [];
          var index = 0;
          for (var i = keys.length - 1; i >= 0; i--) {
            pinArray[index] = [];
            pinArray[index] = data[keys[i]];
            index++;
          }
          console.log("历史拼单array：", pinArray);
          if (pinArray.length > 0) {
            that.setData({
              pinHistoryData: pinArray
            });
          }
        }
      }
    });

    this.loadCommentList(topicid, 1);


  },

  //读取所有评论
  loadCommentList: function (gid, page) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "ordercommentall",
        goods_id: gid,
        page: page,
        num: 10
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("商品评论：", data);
        if (data && data.length > 0) {
          data.forEach(function (m, i) {
            m.pinglun.date = util.formatTime(new Date(parseInt(m.pinglun.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },
  //读取动态页所有评论
  loadTopicCommentList: function (topicid, page) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccommentlist",
        id: topicid,
        page: page,
        num: 10
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("商品评论topiccommentlist：", data);
        if (data && data.length > 0) {
          data.forEach(function (m, i) {
            m.date = util.formatTime(new Date(parseInt(m.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },


  getLoginInfo: function () {
    var that = this;
    app.getLoginUserInfo(function (res) {
      console.log("啊啊啊啊", res);
      if (res && res != -1) {

        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.openid
        })
        that.userinfo = res;

      } else {
        wxAuthFail = true;
      }
      that.load();
    })
  },



  //是否已关注
  //uid是关注者  fid是被关注者
  isFollow: function (uid, fid) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "isaction",
        uid: uid,
        fid: fid
      },
      success: function (responseData) {
        var data = responseData.data;
        if (data[0].rel == 2) {
          that.setData({
            isFollow: true
          });
        }
      }
    });
  },
  //关注
  addFollow: function (e) {
    if (wxAuthFail) {
      app.goAuthorization();
      return;
    }
    var that = this;
    var uid = e.currentTarget.dataset.uid;
    var fid = e.currentTarget.dataset.fid;
    var token = e.currentTarget.dataset.token;
    var privatekey = utilMd5.hexMD5(uid + 'addaction' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "addaction",
        uid: uid,
        tuid: fid,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        if (data.res === true) {
          app.dialog(that.data.tc == 1 ? '關註成功' : '关注成功', 'success');
          that.setData({
            isFollow: true
          });
        } else {
          app.dialog(that.data.tc == 1 ? '關註失敗' : '关注失败', 'loading');
        }
      }
    });
  },
  //取消关注
  cancelFollow: function (e) {

    var that = this;
    var uid = e.currentTarget.dataset.uid;
    var fid = e.currentTarget.dataset.fid;
    var token = e.currentTarget.dataset.token;
    var privatekey = utilMd5.hexMD5(uid + 'delaction' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "delaction",
        uid: uid,
        tuid: fid,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        if (data.res === true) {
          that.setData({
            isFollow: false
          });
          app.dialog(that.data.tc == 1 ? '取消關註成功' : '取消关注成功', 'success');
        } else {
          app.dialog(that.data.tc == 1 ? '取消關註失敗' : '取消关注失败', 'loading');
        }
      }
    });
  },
  //是否已赞
  isLike: function (uid) {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "isliketopic",
        uid: uid,
        topicid: topicid
      },
      success: function (responseData) {
        var data = responseData.data;
        if (data.res === true) {
          that.setData({
            isLiked: true
          });
        }
      }
    });
  },

  //赞列表
  getZanList: function () {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiclikeuser",
        topicid: that.data.data.id,
        cuid: uid,
        page: 1,
        num: 100
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("赞列表数据：", data);
        if (!data.msg) {
          that.setData({
            likeuser: data
          });
        } else {
          that.setData({
            likeuser: []
          });
        }
      }
    });
  },

  //赞
  addLike: function (e) {
    if (wxAuthFail) {
      app.goAuthorization();
      return;
    }

    var that = this;
    var uid = e.currentTarget.dataset.uid;
    var token = e.currentTarget.dataset.token;
    var privatekey = utilMd5.hexMD5(uid + 'liketopic' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "liketopic",
        uid: uid,
        topicid: topicid,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        console.log("赞动作结果：", data);
        if (data.res === true) {
          that.setData({
            isLiked: true
          });
          app.dialog(that.data.tc == 1 ? '贊成功' : '赞成功', 'success', that.getZanList());
        } else {
          app.dialog(that.data.tc == 1 ? '贊失敗' : '赞失败', 'loading');
        }
      }
    });
  },
  //取消赞
  cancelLike: function (e) {
    var that = this;
    var uid = e.currentTarget.dataset.uid;
    var token = e.currentTarget.dataset.token;
    var privatekey = utilMd5.hexMD5(uid + 'delliketopic' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "delliketopic",
        uid: uid,
        topicid: topicid,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        if (data.res === true) {
          that.setData({
            isLiked: false
          });
          app.dialog(that.data.tc == 1 ? '取消贊成功' : '取消赞成功', 'success', that.getZanList());
        } else {
          app.dialog(that.data.tc == 1 ? '取消贊失敗' : '取消赞失败', 'loading');
        }
      }
    });
  },
  //评论
  inputMessage: function (e) {
    //把评论内容绑定到提交按钮上
    var val = e.detail.value;
    this.setData({
      commentMsg: val
    })
  },
  changeReplyid: function (e) {
    var val = e.currentTarget.dataset.id;
    var replyusername = e.currentTarget.dataset.uname;
    this.setData({
      replyid: val,
      commentMsg: this.data.tc == 1 ? '@回復' : '@回复' + replyusername + ':'
    })
  },


  inputFinish: function (e) {
    var comment = e.detail.value;
    console.log("输入信息：" + comment);
    this.setData({
      commentValue: comment
    })
  },
  showCommentView: function (e) {
    this.setData({
      hide_commentview: false,
      data_id: e.currentTarget.dataset.id
    })
  },
  hideCommentView: function () {
    this.setData({
      hide_commentview: true
    })
  },
  addComment: function (e) {
    if (wxAuthFail) {
      app.goAuthorization();
      return;
    }

    var that = this;
    var uid = e.currentTarget.dataset.uid ? e.currentTarget.dataset.uid : that.data.uid;
    var token = e.currentTarget.dataset.token ? e.currentTarget.dataset.token : that.data.token;
    var catatype = e.currentTarget.dataset.catatype;
    var replyid = e.currentTarget.dataset.replyid;
    var message = e.currentTarget.dataset.message ? e.currentTarget.dataset.message : that.data.commentValue;
    if (!message) {
      app.dialog(that.data.tc == 1 ? '請輸入內容' : '请输入内容', 'loading');
      return;
    }
    var privatekey = utilMd5.hexMD5(uid + 'topiccomment' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiccomment",
        uid: uid,
        id: topicid,
        type: catatype,
        replyid: replyid,
        message: message,
        privatekey: privatekey
      },
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;
        var txt = replyid > 0 ? (that.data.tc == 1 ? '回復' : '回复') : (that.data.tc == 1 ? '評論' : '评论');
        if (data.msg === "true") {
          that.setData({
            isLiked: true
          });
          that.setData({
            commentMsg: ''
          })

          app.dialog(txt + that.data.tc == 1 ? '成功' : '成功', 'success', that.refreshPage());
        } else {
          app.dialog(txt + that.data.tc == 1 ? '失敗' : '失败', 'loading');
        }
      }
    });
  },
  //投诉
  complain: function (e) {
    app.dialog(this.data.tc == 1 ? '投訴成功' : '投诉成功', 'success');
  },
  //页面分享
  onShareAppMessage: function () {
    var invUid = this.data.uid ? this.data.uid : '';
    var linkcode = this.data.data.linkcode ? this.data.data.linkcode : linkcode;
    var showcomments = this.data.showcomments || ''
    var path = '/pages/detail/detail?topicid=' + topicid + '&inviteuid=' + invUid + "&linkcode=" + linkcode + "&showcomments=" + showcomments;
    console.log("分享给好友：" + path);
    var title = topictitle ? topictitle : uname;
    if (util.orgid == 15671) {
      title = '求职，企业招聘，人才培训……壹号人才欢迎您';
    }
    return {
      title: title,
      path: path
    };
  },

  copyLink: function () {
    var that = this;
    wx.setClipboardData({
      data: that.data.data.alt,
      success: function (res) {
        wx.showToast({
          title: that.data.tc == 1 ? '已復制到剪貼板' : '已复制到剪贴板',
        })
      }
    })
  },


  shareToPengyouquan: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log('海报图片链接：' + e.currentTarget.dataset.imgsrc);

    // shareImgUrl = base64.encode(shareImgUrl);
    // var url = "/pages/haibao-page/haibao-page?imgUrl=" + shareImgUrl;
    // wx.navigateTo({ url: url });

    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  showEWM: function (e) {
    console.log("！！！！！图片：", this.data.data.photoArr);
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: this.data.data.photoArr
    })
  },
  //刷新当前页
  refreshPage: function () {
    wx.redirectTo({
      url: '/pages/detail/detail?topicid=' + topicid
    })
  },

  //减少动作
  reduceAction: function (e) {
    var newInputValue = this.data.countValue - 1;
    if (newInputValue < 1) {
      return;
    }
    this.setData({
      countValue: newInputValue
    })
  },
  //增加动作
  addAction: function (e) {
    if (this.data.countValue >= this.data.data.kucun) {
      wx.showToast({
        title: this.data.tc == 1 ? '超出庫存啦' : '超出库存啦',
      });
      return;
    }
    var newInputValue = this.data.countValue + 1;
    this.setData({
      countValue: newInputValue
    })
  },

  jifenHuangou: function (e) {
    var that = this;
    if (wxAuthFail) {
      wx.login({
        success: function (e) {
          wx.setStorageSync('code', e.code);
        },
        fail: function (e) {
          console.log("wx.login fail:", e);
        }
      });
      wx.getUserProfile({
        desc: "下单需要",
        success: function (res) {
          console.log("用户已授权：", res);
          app.wxAuthRequest(res, function (res) {
            if (res != -1) {
              that.getLoginInfo();
            }
          });
        },
        fail: function (err) {
          console.log("wx.getUserInfo fail:", err);
        }
      })
    } else {
      if (this.isLogin) {
        this.buyAction(e);
      } else {
        var membercard = this.userinfo.mobile;
        console.log(membercard);
        if (!membercard) {
          wx.navigateTo({
            url: '/pages/join/join?',
          })
        } else {
          wx.navigateTo({
            url: '/pages/login/login?membercard=' + membercard,
          })
        }
      }
    }
  },

  buyAction: function (e) {

    if (this.data.guigeData.length > 0 && !this.data.selectGuige) {
      var toastStr = this.data.tc == 1 ? "請選擇" : "请选择 " + this.data.data.guige;
      wx.showModal({
        title: this.data.tc == 1 ? '提示' : "提示",
        content: toastStr,
        showCancel: false
      })
    } else {
      if (wxAuthFail) {
        var that = this;
        wx.login({
          success: function (e) {
            wx.setStorageSync('code', e.code);
          },
          fail: function (e) {
            console.log("wx.login fail:", e);
          }
        });
        wx.getUserProfile({
          desc: "下单需要",
          success: function (res) {
            console.log("用户已授权：", res);
            app.wxAuthRequest(res, function (res) {
              if (res != -1) {
                that.getLoginInfo();
              }
            });
          },
          fail: function (err) {
            console.log("wx.getUserInfo fail:", err);
          }
        })

      } else {
        if (this.isLogin) {
          var goodsInfo = this.buildGoodsInfo();
          var addItem = JSON.stringify([goodsInfo]);
          var url = "/pages/order-confirm/order-confirm?goodsArr=" + addItem;
          wx.navigateTo({ url: url });
        } else {
          var membercard = this.userinfo.mobile;
          console.log(membercard);
          if (!membercard) {
            wx.navigateTo({
              url: '/pages/join/join?',
            })
          } else {
            wx.navigateTo({
              url: '/pages/login/login?membercard=' + membercard,
            })
          }
        }
      }
    }
  },


  //加入购物车
  addToGouwuche: function () {
    var that = this;
    console.log('--------------->>>>>>>>>>', this.data.data)
    if (that.data.showAttribute == true) {
      that.hideModal();
    }
    var good = this.data.data;

    if (good.kucun <= 0) {
      wx.showToast({
        title: that.data.tc == 1 ? '庫存為空' : '库存为空',
      });
      return;
    } else {
      if (this.data.guigeData.length > 0 && !this.data.selectGuige) {
        var toastStr = this.data.tc == 1 ? "請選擇" : "请选择 " + this.data.data.guige;
        wx.showModal({
          title: this.data.tc == 1 ? '提示' : "提示",
          content: toastStr,
          showCancel: false
        })
      } else {
        var gwc_datas = wx.getStorageSync('gwc_datas');
        if (!gwc_datas) {
          gwc_datas = [];
        }

        var goodsInfo = this.buildGoodsInfo();
        var addItem = [goodsInfo];
        var hasSameGoods = false;
        if (gwc_datas.length > 0) {
          for (var i = gwc_datas.length - 1; i >= 0; i--) {
            if (gwc_datas[i].id == goodsInfo.id) {
              if (this.data.guigeData.length > 0) {
                if (gwc_datas[i].selGuige.id == goodsInfo.selGuige.id) {
                  hasSameGoods = true;
                  gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
                }
              } else {
                hasSameGoods = true;
                gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
              }
            }
          }
        }

        if (!hasSameGoods) {
          gwc_datas = addItem.concat(gwc_datas);
          var count = this.data.gwc_count + 1;
          this.setData({
            gwc_count: count
          })
        }


        wx.setStorageSync('gwc_datas', gwc_datas);
        var contentname = this.data.tc == 1 ? '已成功加到購物車' : '已成功加到购物车';
        wx.showToast({
          title: contentname,
        })
        // var confirmTextname = this.data.tc == 1 ? '去結算' : '去结算';
        // wx.showModal({
        //   title: '提示',
        //   content: contentname,
        //   cancelText: '再看看',
        //   confirmText: confirmTextname,
        //   success:function(res){
        //     if(res.confirm){
        //       wx.reLaunch({
        //         url: '/pages/gouwuche/gouwuche',
        //       })
        //     }
        //   }
        // })
      }

    }

  },

  buildGoodsInfo: function () {
    var good = this.data.data;
    var goodsInfo = {};
    goodsInfo.id = good.id;
    goodsInfo.ghsid = good.postuid;
    goodsInfo.title = good.topictitle;
    goodsInfo.titleofenglish = good.titleofenglish;
    goodsInfo.def_img = good.photoscbk[0].photo;
    goodsInfo.sel = true;
    goodsInfo.guigeName = good.guige ? good.guige : '';
    goodsInfo.selGuige = this.data.selectGuige;
    if (good.pin == 1) {//拼单商品
      goodsInfo.price = good.pinprice;
    } else {
      goodsInfo.price = this.data.selectGuige ? this.data.selectGuige.price : good.sellprice;
    }
    goodsInfo.yunfei = good.yunfei;
    goodsInfo.kucun = good.kucun;
    goodsInfo.buycount = this.data.countValue;
    goodsInfo.source = good.source;
    goodsInfo.pin = good.pin;//这里加是否是拼单商品标记
    goodsInfo.pinzong = good.pinzong;//这个是拼单的 期数，通常一天为一个拼单周期
    goodsInfo.linkcode = (good.linkcode ? good.linkcode : linkcode);//商品唯一32位id
    // goodsInfo.attribute = good.attribute ? good.attribute : '';//商品属性
    goodsInfo.groupId = this.data.data.groupId;
    goodsInfo.titleArray = good.titleArray;
    goodsInfo.RecMark = good.RecMark;//推荐标记

    // goodsInfo.zhekou = good.zhekou;//折扣
    // goodsInfo.starttime = good.starttime;//折扣开始时间
    // goodsInfo.endtime = good.endtime;//折扣结束时间
    if (this.isLogin) {
      goodsInfo.memberprice = good.zhekouprice ? good.zhekouprice : good.memberprice;//折扣价
      goodsInfo.zhekoushow = good.zhekouprice ? 1 : 0;//是否有折扣价
    } else {
      goodsInfo.memberprice = good.memberprice;//推荐标记
    }

    goodsInfo.sellscore = good.sellscore; //換購積分
    goodsInfo.selltype = good.selltype; // 商品购买方式 0:只能花钱买 1:只能用积分换购 2:既要花钱，还要用积分
    return goodsInfo;

  },

  //跳转
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    //如果是 立即购买 或 咨询 则需要判断是否已授权登录
    if (wxAuthFail && (url.indexOf('order-confirm') >= 0)) {
      app.goAuthorization();
      return;
    }

    var pageIndex = getCurrentPages().length;
    if (pageIndex >= 5) {
      wx.redirectTo({ url: url, fail: function (e) { console.log(e) } })
    } else {
      wx.navigateTo({ url: url, fail: function (e) { console.log(e) } })
    }
  },
  clickImg: function (e) {
    this.setData({
      "stv.src": e.currentTarget.dataset.imgsrc,
      "stv.display": "true"
    });
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },
  //跳转
  goAtherPageRelaunch: function (e) {
    var url = e.currentTarget.dataset.link;
    //如果是 立即购买 或 咨询 则需要判断是否已授权登录
    if (wxAuthFail && (url.indexOf('gouwuche/gouwuche') >= 0)) {
      app.goAuthorization();
      return;
    }
    if (util.orgid == '12545') {
      wx.navigateTo({ url: url });
    } else {
      wx.reLaunch({ url: url });

    }
  },
  clickImg: function (e) {
    // this.setData({
    //     "stv.src":e.currentTarget.dataset.imgsrc,
    //     "stv.display":"true"
    // });
    var imgListType = e.currentTarget.dataset.imglist;
    var imgList = [];
    if (imgListType == "1") {
      var photo = this.data.data.photoscbk;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat([photo[i].photo]);
      }
    } else if (imgListType == "2") {
      var photo = this.data.data.link_works;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    } else if (imgListType == "3") {
      var photo = this.data.data.link_relations;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    }
    console.log(imgList);
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: imgList
    })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      path = path.slice(6);
    }
    if (path) {
      wx.reLaunch({
        url: path,
      })
    }
  },


  //删除数据
  delDataAction: function () {
    this.setData({
      modalHidden: false,
    })
  },

  modalBindaconfirm: function () {
    this.deleteData();
    this.setData({
      modalHidden: true,
    })
  },
  modalBindcancel: function () {
    this.setData({
      modalHidden: true
    })
  },

  deleteData: function () {

    var that = this;

    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + 'deltopic' + token);//私钥
    var ownerId = this.data.data.user.uid;
    var params = {
      ac: "deltopic",
      privatekey: privatekey,
      uid: ownerId,
      edituid: uid,
      topicid: that.data.data.id
    }
    console.log("deltopic params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {

        var result = responseData.data;
        console.log("删除数据：", result);
        if (result.res) {
          app.dialogToast(that.data.tc == 1 ? '刪除成功' : "删除成功", 'success', function () {
            // wx.reLaunch({
            //   url: '/pages/index/index',
            // })
            wx.navigateBack({
              delta: 1
            })
          });
        }
      }
    });
  },

  setTopAction: function (e) {

    var that = this;
    var toastStr = that.data.tc == 1 ? '置頂成功' : "置顶成功";
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var level = 1;
    var ac = 'addtop';
    if (that.data.data.addtop >= 1) {
      ac = 'unaddtop';
      level = 0;
      toastStr = that.data.tc == 1 ? '已取消置頂' : "已取消置顶";
    }
    var privatekey = utilMd5.hexMD5(uid + ac + token);//私钥
    var ownerId = this.data.data.user.uid;
    var params = {
      ac: ac,
      privatekey: privatekey,
      uid: ownerId,
      edituid: uid,
      id: that.data.data.id,
      level: level
    }

    params.ac = ac;

    console.log("置顶／取消置顶 params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {

        var result = responseData.data;
        console.log(toastStr, result);
        if (result.res) {
          app.dialogToast(toastStr, 'success');
          var detailData = that.data.data;
          detailData.addtop = level;
          that.setData({
            data: detailData
          })
        }
      }
    });
  },

  editDataAction: function () {
    var that = this;
    var topicType = that.data.data.topictype;
    var pageUrl = '';
    var topicData = base64.encode(JSON.stringify(that.data.data));
    // console.log("要修改的数据：", topicData);
    if (topicType == 4) {//商品
      pageUrl = "/pages/release-goods/release-goods?data=" + topicData;
    } else if (topicType == 6) {//作品
      pageUrl = "/pages/release-zp/release-zp?data=" + topicData;
    } else if (topicType == 7 || topicType == 2) {//相册／动态
      pageUrl = "/pages/release-jk/release-jk?data=" + topicData;
    } else if (topicType == 8) {//展览
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 9) {//文字
      pageUrl = "/pages/release-wz/release-wz?data=" + topicData;
    } else if (topicType == 11) {//视频
      pageUrl = "/pages/release-sp/release-sp?data=" + topicData;
    } else if (topicType == 13) {//艺术年表
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 14) {//荣誉奖项
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 15) {//收藏拍卖
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 16) {//公益捐赠
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 17) {//媒体
      pageUrl = "/pages/release-mt/release-mt?data=" + topicData;
    } else if (topicType == 18) {//出版刊登
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    }

    if (pageUrl) {
      var pages = getCurrentPages();
      var curPageIndex = pages.length;
      if (curPageIndex >= 5) {
        wx.redirectTo({
          url: pageUrl,
        })
      } else {
        wx.navigateTo({
          url: pageUrl,
        })
      }

    }
  },

  getGuigeData: function (g_id) {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodsguige",
        "goods_id": g_id
      },
      success: function (responseData) {
        console.log("商品规格：", responseData.data)
        if (!responseData.data.msg) {
          var selGuige = responseData.data[0];
          var good = that.data.data;
          good.guigelist = responseData.data;
          that.setData({
            guigeData: responseData.data,
            selectGuige: selGuige,
            data: good,
            good: good
          })
        }
      }
    });
  },

  guigeSelect: function (e) {
    var selGuige = e.currentTarget.dataset.data;

    this.setData({
      // actionSheetHidden: !this.data.actionSheetHidden,
      selectGuige: selGuige,
      allprice: (this.data.buynum * (selGuige.price / 100)).toFixed(2),
      oneprice: (selGuige.price / 100).toFixed(2)
    })
  },


  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },


  //获取运费设置
  getYunfeiSet: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        console.log("运费：", responseData);
        var data = responseData.data;
        if (!data.msg) {
          let myCion = parseInt(data[0].mianfei);
          that.setData({
            my_cion: myCion
          })
        }

      }
    });
  },
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },


  //判断商品是否有属性
  getAttribute: function () {
    var that = this;
    var good = this.data.data;
    console.log("Good", good);
    console.log("addGoods", good.groupId);
    if (good.kucun <= 0) {
      wx.showToast({
        title: that.data.tc == 1 ? '庫存為空' : '库存为空',
      });
      return;
    } else {

      that.showModal();
      var group = good.groupId;
      if (group == 0) {
        that.addToGouwuche();
      } else {
        var params = {
          publickey: util.publiccode,
          ac: "getAttribute",
          orgid: util.orgid,
          uid: that.data.uid,
          groupId: group
        };

        console.log("商品属性请求参数：", params);
        util.api({
          data: params,
          success: function (responseData) {
            console.log("商品属性:", responseData.data);
            var result = responseData.data;
            if (result.length > 0) {
              var groups = [];
              for (var i = 0; i < result.length; i++) {
                var exist = false;
                if (i == 0) {
                  let groupObj = { groupId: '', groupName: "", subList: [] };
                  groupObj.groupId = result[i].groupId;
                  groupObj.groupName = result[i].groupName;
                  let subObj = {};
                  subObj.attributeId = result[i].attributeId;
                  subObj.attributeName = result[i].attributeName;
                  subObj.attributePrice = result[i].attributePrice;
                  subObj.optionTypes = result[i].optionTypes;
                  subObj.checked = false;
                  groupObj.subList.push(subObj);
                  groups.push(groupObj);
                  continue
                } else {
                  for (var j = 0; j < groups.length; j++) {
                    if (groups[j].groupId == result[i].groupId) {
                      let subObj = {};
                      subObj.attributeId = result[i].attributeId;
                      subObj.attributeName = result[i].attributeName;
                      subObj.attributePrice = result[i].attributePrice;
                      subObj.optionTypes = result[i].optionTypes;
                      subObj.checked = false;
                      groups[j].subList.push(subObj);
                      exist = true;
                      break
                    }
                  }
                  if (!exist) {
                    let groupObj = { groupId: '', groupName: "", subList: [] };
                    groupObj.groupId = result[i].groupId;
                    groupObj.groupName = result[i].groupName;
                    let subObj = {};
                    subObj.attributeId = result[i].attributeId;
                    subObj.attributeName = result[i].attributeName;
                    subObj.attributePrice = result[i].attributePrice;
                    subObj.optionTypes = result[i].optionTypes;
                    subObj.checked = false;
                    groupObj.subList.push(subObj);
                    groups.push(groupObj);
                  }

                }


              }
              console.log('groups---->', groups);


              good.attributeGroups = groups;
              that.setData({
                childArr: [],
                attributeGroupsOriginal: result,
                mainfoodArray: [],
                drinksArray: [],
                prefoodArray: [],
                attributeGroups: groups,
                // showAttributeNew: true,
                showAttribute: true,
                good: good
              });
              that.markAttrGroups();
              that.prefoodInitial();
            }
          }
        });
      }

    }

  },

  hideAttribute: function () {
    var that = this;
    that.hideModal();
  },


  radioChange: function (e) {
    var that = this
    console.log('radio发生change事件，携带value值为：', e.currentTarget.dataset)
    var Groups = this.data.attributeGroups;
    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (Groups[i].groupId == e.currentTarget.dataset.groupid.substring(0, 3) && Groups[i].subList[j].attributeId == e.currentTarget.dataset.value) {
          if (Groups[i].groupId == e.currentTarget.dataset.groupid) {
            Groups[i].subList[j].checked = true;
          }
          that.checkChildArray(e);
          if (e.currentTarget.dataset.groupid.substring(0, 3) == '300') {
            that.addDrink(e)
          }
          if (e.currentTarget.dataset.groupid == '200') {
            that.addMainfood(e)
          }
          if (e.currentTarget.dataset.groupid == '100') {
            that.addprefood(e)
          }
        } else if (Groups[i].groupId == e.currentTarget.dataset.groupid) {
          Groups[i].subList[j].checked = false
        }
      }

    }

    this.setData({
      attributeGroups: Groups,
    });


  },

  addDrink(e) {
    var that = this;
    console.log('addDrink', e.currentTarget.dataset);
    var Groups = that.data.attributeGroups;
    var drinksArray = that.data.drinksArray;
    that.data.addDrink = true;

    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        console.log('substring(4, 5)', e.currentTarget.dataset.groupid.substring(4, 5));
        if (e.currentTarget.dataset.groupid.length > 3 && e.currentTarget.dataset.groupid.substring(0, 3) == Groups[i].groupId && e.currentTarget.dataset.groupid.substring(4, 5) == Groups[i].subList[j].attributeId) {
          //二级字串
          console.log('e.currentTarget.dataset.groupid.substring(0, 3)', e.currentTarget.dataset.groupid)
          let itemOb = {};
          itemOb.groupId = e.currentTarget.dataset.groupid;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = e.currentTarget.dataset.value;
          itemOb.attributeName = e.currentTarget.dataset.attributename;
          itemOb.attributeNameEng = e.currentTarget.dataset.attributenameEng;

          if (that.data.good.gtype == '412440' && drinksArray.length < 2) {
            drinksArray.push(itemOb);
            console.log('add1')
          } else if (that.data.good.gtype != '412440' && drinksArray.length < 1) {
            drinksArray.push(itemOb);
            console.log('add2')
          } else {
            console.log('add3')
            drinksArray.push(itemOb);
            drinksArray.splice(0, 1);
          }

        } else if (that.data.existChildArr == false && e.currentTarget.dataset.groupid == Groups[i].groupId && e.currentTarget.dataset.value == Groups[i].subList[j].attributeId) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          if (that.data.good.gtype == '412440' && drinksArray.length < 2) {
            drinksArray.push(itemOb);
          } else if (that.data.good.gtype != '412440' && drinksArray.length < 1) {
            drinksArray.push(itemOb);

          } else {
            drinksArray.push(itemOb);
            drinksArray.splice(0, 1);
          }
        } else {

        }
      }
      if (e.currentTarget.dataset.groupid == Groups[i].groupId) {
        console.log('Groups[i]', Groups[i])

      }
    }
    console.log('drinksArray', drinksArray)
    this.setData({
      attributeGroups: Groups,
      drinksArray: drinksArray
    });


  },

  delDrink: function (e) {
    console.log('delDrink', e.currentTarget.dataset);
    var that = this;
    var drinksArray = that.data.drinksArray;
    for (var i = 0; i < drinksArray.length; i++) {
      if (i == e.currentTarget.dataset.idx) {
        drinksArray.splice(i, 1);
      }
    }
    console.log('drinksArray', drinksArray)
    this.setData({
      drinksArray: drinksArray
    });

  },
  addMainfood(e) {
    var that = this;
    console.log('addDrink', e.currentTarget.dataset);
    var Groups = that.data.attributeGroups;
    var mainfoodArray = that.data.mainfoodArray;
    that.data.addDrink = true;

    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (e.currentTarget.dataset.groupid == Groups[i].groupId && e.currentTarget.dataset.value == Groups[i].subList[j].attributeId) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          if (mainfoodArray.length < 2) {
            mainfoodArray.push(itemOb);

          } else {
            mainfoodArray.push(itemOb);
            mainfoodArray.splice(0, 1);
          }
        }
      }
      if (e.currentTarget.dataset.groupid == Groups[i].groupId) {
        console.log('Groups[i]', Groups[i])

      }
    }
    console.log('mainfoodArray', mainfoodArray)
    this.setData({
      attributeGroups: Groups,
      mainfoodArray: mainfoodArray
    });


  },

  delMainfood: function (e) {
    console.log('delMainfood', e.currentTarget.dataset);
    var that = this;
    var mainfoodArray = that.data.mainfoodArray;
    for (var i = 0; i < mainfoodArray.length; i++) {
      if (i == e.currentTarget.dataset.idx) {
        mainfoodArray.splice(i, 1);
      }
    }
    console.log('mainfoodArray', mainfoodArray)
    this.setData({
      mainfoodArray: mainfoodArray
    });

  },

  addprefood(e) {
    var that = this;
    console.log('addprefood', e.currentTarget.dataset);
    var Groups = that.data.attributeGroups;
    var prefoodArray = that.data.prefoodArray;
    that.data.addDrink = true;

    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (e.currentTarget.dataset.groupid == Groups[i].groupId && e.currentTarget.dataset.value == Groups[i].subList[j].attributeId) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          if (prefoodArray.length < 3) {
            prefoodArray.push(itemOb);

          } else {
            prefoodArray.push(itemOb);
            prefoodArray.splice(2, 1);
          }
        }
      }
      if (e.currentTarget.dataset.groupid == Groups[i].groupId) {
        console.log('Groups[i]', Groups[i])

      }
    }
    console.log('addprefood', prefoodArray)
    this.setData({
      attributeGroups: Groups,
      prefoodArray: prefoodArray
    });


  },

  delprefood: function (e) {
    console.log('delprefood', e.currentTarget.dataset);
    var that = this;
    var prefoodArray = that.data.prefoodArray;
    for (var i = 2; i < 3; i++) {
      if (i == e.currentTarget.dataset.idx) {
        prefoodArray.splice(i, 1);
      }
    }
    console.log('prefoodArray', prefoodArray)
    this.setData({
      prefoodArray: prefoodArray
    });

  },
  //属性标记
  markAttrGroups: function () {
    var that = this;
    var Groups = that.data.attributeGroups;
    for (var i = 0; i < Groups.length; i++) {
      //英文属性名
      if (Groups[i].groupName.indexOf('\\') > 0) {
        let gnameArr = Groups[i].groupName.split('\\');
        Groups[i].groupName = gnameArr[0];
        Groups[i].groupNameEng = gnameArr[1];
      } else {
        Groups[i].groupNameEng = '';
      }
      for (var j = 0; j < Groups[i].subList.length; j++) {
        let title = Groups[i].subList[j].attributeName
        if (title.indexOf("|") > 0) {
          let Arr = title.split('|')
          Groups[i].subList[j].attributeName = Arr[0];
          Groups[i].subList[j].mark = Arr[1];
          //英文属性名
          if (Groups[i].subList[j].attributeName.indexOf('\\') > 0) {
            let nameArr = Groups[i].subList[j].attributeName.split('\\');
            Groups[i].subList[j].attributeName = nameArr[0];
            Groups[i].subList[j].attributeNameEng = nameArr[1];
          } else {
            Groups[i].subList[j].attributeNameEng = '';
          }
          console.log('markAttrGroups', Groups[i].subList[j].mark)
          console.log('markAttrGroups---attributeNameEng', Groups[i].subList[j].attributeNameEng)
        } else {
          //英文属性名
          if (Groups[i].subList[j].attributeName.indexOf('\\') > 0) {
            let nameArr = Groups[i].subList[j].attributeName.split('\\');
            Groups[i].subList[j].attributeName = nameArr[0];
            Groups[i].subList[j].attributeNameEng = nameArr[1];
          } else {
            Groups[i].subList[j].attributeNameEng = '';
          }
        }
      }


    }
    that.setData({
      attributeGroups: Groups
    })
  },
  //前菜默认必选项2个
  prefoodInitial() {
    var that = this;
    var Groups = that.data.attributeGroups;
    var prefoodArray = that.data.prefoodArray;
    console.log('prefoodArrayIntial', prefoodArray)
    for (var i = 0; i < Groups.length; i++) {
      for (var j = 0; j < Groups[i].subList.length; j++) {
        if (Groups[i].groupId == '100' && (Groups[i].subList[j].attributeId == '5' || Groups[i].subList[j].attributeId == '4')) {
          Groups[i].subList[j].checked = true;
          let itemOb = {};
          itemOb.groupId = Groups[i].groupId;
          itemOb.groupName = Groups[i].groupName;
          itemOb.groupNameEng = Groups[i].groupNameEng;

          itemOb.attributeId = Groups[i].subList[j].attributeId;
          itemOb.attributeName = Groups[i].subList[j].attributeName;
          itemOb.attributeNameEng = Groups[i].subList[j].attributeNameEng;
          prefoodArray.push(itemOb);
        }
      }

    }
    console.log('prefoodArrayIntial', prefoodArray)
    this.setData({
      prefoodArray: prefoodArray
    });
  },

  checkChildArray: function (e) {
    var that = this;
    var Groups = that.data.attributeGroupsOriginal;
    if (e.currentTarget.dataset.groupid.length == 3) {
      that.setData({
        childArr: [],
        existChildArr: false
      })

    }
    for (var i = 0; i < Groups.length; i++) {
      if (Groups[i].groupId == e.currentTarget.dataset.groupid && Groups[i].attributeId == e.currentTarget.dataset.value && Groups[i].erji) {
        var childArr = Groups[i].erji;
        for (var j = 0; j < childArr.length; j++) {
          childArr[j].checked = false;
          //英文属性名
          if (childArr[j].attributeName.indexOf('\\') > 0) {
            let nameArr = childArr[j].attributeName.split('\\');
            childArr[j].attributeName = nameArr[0];
            childArr[j].attributeNameEng = nameArr[1];
          } else {
            childArr[j].attributeNameEng = '';
          }
        }
        that.setData({
          childArr: childArr,
          existChildArr: true
        })
      }
    }
    console.log("childArr", childArr)

    //更新check状态
    var childArr = that.data.childArr;
    for (var k = 0; k < childArr.length; k++) {
      if (childArr[k].groupId == e.currentTarget.dataset.groupid && childArr[k].attributeId == e.currentTarget.dataset.value) {
        childArr[k].checked = true;
      } else {
        childArr[k].checked = false;
      }
    }

    that.setData({
      childArr: childArr,
      showSubDrink: that.data.existChildArr ? true : false

    })
    // 使页面滚动到底部
    that.pageScrollToBottom();
    if (!that.data.showSubDrink && that.data.existChildArr) {
      that.showSubDrink()

    }
  },

  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    if (util.orgid == 12545) {
      animation.translateY(300).step()
    } else {

      animation.translate(0, 300).scale3d(0, 0, 0).step()
    }
    this.setData({
      animationData: animation.export(),
      showAttribute: util.orgid == 12545 ? true : false,
      showAttribute: util.orgid == 21145 ? true : false,
      showAttribute: util.orgid == 19619 ? true : false,
    })
    setTimeout(function () {
      if (util.orgid == 12545) {
        animation.translateY(0).step()
      } else {
        animation.scale3d(1, 1, 1).step()
        animation.translate(0, 0).step()

      }
      this.setData({
        animationData: animation.export(),
        showAttribute: util.orgid == 12545 ? true : false,
        showAttribute: util.orgid == 21145 ? true : false,
        showAttribute: util.orgid == 19619 ? true : false,
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    var animationbar = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.animationbar = animationbar
    if (util.orgid == 12545) {
      animation.translateY(300).step()
    } else {
      animation.translate(0, 300).scale3d(0, 0, 0).step()
      animationbar.scale3d(2, 2, 2).step()

    }
    this.setData({
      animationData: animation.export(),
      animationDatabar: animationbar.export(),
    })
    setTimeout(function () {
      animationbar.scale3d(1, 1, 1).step()
      this.setData({
        animationData: animation.export(),
        animationDatabar: animationbar.export(),
        showAttribute: false,
        showMoreAct: false,
        showSendTime: false
      })
    }.bind(this), 200)
  },

  //标题标记处理
  markGood: function () {
    var that = this;
    var good = that.data.data;

    let title = good.topictitle;
    if (title.indexOf("+") > 0) {
      //多个子标题
      let navArr = title.split('+');
      console.log('titleArr', navArr)
      for (var j = 0; j < navArr.length; j++) {
        let subStr = navArr[j];
        if (subStr.indexOf("|") > 0) {
          //标题有标志
          let miniArr = subStr.split('|')
          if (!good.titleArray) {
            good.titleArray = [];
          }
          let obj = {}
          obj.title = miniArr[0];
          obj.mark = miniArr[1];
          // 英文标题
          if (obj.title.indexOf('\\') > 0) {
            let langArr = obj.title.split('\\');
            obj.title = langArr[0];
            obj.titleEnglish = langArr[1];
          } else {
            obj.titleEnglish = '';
          }
          good.titleArray.push(obj);
          console.log('topictitle.mark', good.titleArray)
        } else {
          if (!good.titleArray) {
            good.titleArray = [];
          }
          let obj = {}
          obj.title = subStr;
          obj.mark = '';
          // 英文标题
          if (obj.title.indexOf('\\') > 0) {
            let langArr = obj.title.split('\\');
            obj.title = langArr[0];
            obj.titleEnglish = langArr[1];
          } else {
            obj.titleEnglish = '';
          }
          good.titleArray.push(obj);
          console.log('topictitle.mark', good.titleArray)
        }

      }
    } else if (title.indexOf("|") > 0) {
      //一个子标题，标题有标志
      let miniArr = title.split('|')
      if (miniArr.length == 2) {
        if (!good.titleArray) {
          good.titleArray = [];
        }
        let obj = {}
        obj.title = miniArr[0];
        obj.mark = miniArr[1];
        // 英文标题
        if (obj.title.indexOf('\\') > 0) {
          let langArr = obj.title.split('\\');
          obj.title = langArr[0];
          obj.titleEnglish = langArr[1];
        } else {
          obj.titleEnglish = '';
        }
        good.titleArray.push(obj);
        console.log('topictitle.mark', good.titleArray)

      }
      console.log('topictitle.mark', good.titleArray)
    } else {
      //一个子标题，标题无标志
      if (!good.titleArray) {
        good.titleArray = [];
      }
      let obj = {}
      obj.title = good.topictitle;
      obj.mark = '';
      // 英文标题
      if (obj.title.indexOf('\\') > 0) {
        let langArr = obj.title.split('\\');
        obj.title = langArr[0];
        obj.titleEnglish = langArr[1];
      } else {
        obj.titleEnglish = '';
      }
      good.titleArray.push(obj);
      console.log('topictitle.mark', good.titleArray)
    }


    that.setData({
      good: good
    })
  },
  //标题推荐标记处理
  markGoodWithRec: function () {
    var that = this;
    var good = that.data.data;

    let title = good.topictitle;
    if (title.indexOf(":") > 0) {
      let miniArr = title.split(':')
      if (miniArr.length == 2) {
        if (!good.RecMark) {
          good.RecMark = [];
        }
        let obj = {}
        obj.title = miniArr[0];
        obj.mark = miniArr[1];
        good.topictitle = miniArr[0];
        good.RecMark.push(obj);
        console.log('topictitle.RecMark', good.RecMark)

      } else {

      }
      console.log('topictitle.RecMark', good.RecMark)
    } else {
      if (!good.RecMark) {
        good.RecMark = [];
      }
      let obj = {}
      obj.title = good.topictitle;
      obj.mark = '';

      good.RecMark.push(obj);
      console.log('topictitle.RecMark', good.RecMark)
    }


    that.setData({
      good: good
    })
  },
  pageScrollToBottom: function () {
    var that = this;
    wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      // wx.pageScrollTo({
      //   scrollTop: rect.bottom
      // });
      that.setData({
        scrollTop: rect.bottom
      })
      console.log("pageScrollToBottom", rect.bottom)
    }).exec()
  },



  getghs: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: 1,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        for (var i = 0; i < result.length; i++) {
          if (result[i].gcataid == that.data.data.gtype.substring(0, 3)) {
            var uid = result[i].uid;
            var title = result[i].username;
            that.setData({
              ghsid: result[i].uid,
              ghsname: result[i].username,
            });
          }
        }
      }
    });
  },
  //
  showSubDrink: function () {
    this.showModalSub();
  },

  showModalSub: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationDatasub: animation.export(),
      showSubDrink: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDatasub: animation.export(),
        showSubDrink: true
      })
    }.bind(this), 200)
  },

  hideModalSub: function () {
    var that = this;
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationDatasub: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationDatasub: animation.export(),
        showSubDrink: false
      })
      that.pageScrollToBottom();
    }.bind(this), 200);
  },

  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },


  popupGuige: function (e) {
    console.log("selectGuige")
    console.log(e.currentTarget.dataset.good)
    var that = this;
    var good = e.currentTarget.dataset.good;
    that.setData({
      good: good
    })
    that.showModal()
    that.getAttribute(e);
  },
  guigeSelect: function (e) {
    var that = this;
    var selGuige = e.currentTarget.dataset.guige;
    var index = e.currentTarget.dataset.idx;
    var good = that.data.good;
    good.selGuige = selGuige;
    console.log("selGuige", good.selGuige)
    good.guigelist[index].checked = true;
    var list = good.guigelist;
    for (var i = 0; i < list.length; i++) {
      if (i != index) {
        list[i].checked = false
      }
    }
    good.guigelist = list;
    this.setData({
      good: good
    })



    this.setData({
      // actionSheetHidden: !this.data.actionSheetHidden,
      selectGuige: selGuige,
      allprice: (this.data.buynum * (selGuige.price / 100)).toFixed(2),
      oneprice: (selGuige.price / 100).toFixed(2)
    })
  },
  selectAttr: function (e) {
    var that = this;
    var gi = e.currentTarget.dataset.groupindex;
    var ai = e.currentTarget.dataset.attrindex;
    var good = that.data.good;
    var groups = good.attributeGroups;
    console.log(e.currentTarget.dataset)
    groups[gi].subList[ai].checked = true;

    console.log("groups[gi].subList[ai]", groups[gi].subList[ai])
    console.log("subList[ai]", groups[gi].subList[ai])
    console.log("groups[gi]", groups[gi])
    var list = groups[gi].subList;
    for (var i = 0; i < list.length; i++) {
      if (i != ai) {
        list[i].checked = false
      }
    }
    if (!good.attribute) {
      good.attribute = [];
    }

    if (!groups[gi].selectedList) {
      groups[gi].selectedList = [];
    }

    var optionTypes = groups[gi].subList[ai].optionTypes;
    console.log("groups[gi].selectedList", groups[gi].selectedList.length)
    if (groups[gi].selectedList.length >= optionTypes) {

      wx.showToast({
        title: '只能選' + optionTypes + '個',
      })
      return;
    }

    // for (var i = 0; i < good.attribute.length; i++) {
    //   if (good.attribute[i].groupId == groups[gi].groupId) {
    //     good.attribute.splice(i, 1); // 去除旧属性项       
    //   }
    //   console.log("del")
    // }

    let itemOb = {};
    itemOb.groupId = groups[gi].groupId;
    itemOb.groupName = groups[gi].groupName;
    itemOb.groupNameEng = groups[gi].groupNameEng;
    itemOb.attributeId = list[ai].attributeId;
    itemOb.attributeName = list[ai].attributeName;
    itemOb.attributeNameEng = list[ai].attributeNameEng;
    itemOb.attributePrice = list[ai].attributePrice;
    console.log("itemOb", itemOb)
    good.attribute.push(itemOb);// 添加新属性
    groups[gi].selectedList.push(itemOb);// 添加新属性

    console.log("good.attribute", good.attribute)
    if (!good.jiaqian) {
      good.jiaqian = 0
    }
    good.jiaqian += parseInt(list[ai].attributePrice);

    groups[gi].subList = list;
    good.attributeGroups = groups;
    this.setData({
      good: good
    })
  },

  delAttr: function (e) {
    var that = this;
    var gi = e.currentTarget.dataset.groupindex;
    var si = e.currentTarget.dataset.selectindex;
    var good = that.data.good;
    var groups = good.attributeGroups;
    var attribute = good.attribute;
    console.log(e.currentTarget.dataset)
    console.log("groups[gi].selectedList[si]", groups[gi].selectedList[si])
    console.log("selectedList[si]", groups[gi].selectedList[si])
    console.log("groups[gi]", groups[gi])
    var delItem = groups[gi].selectedList[si];
    for (var i = 0; i < attribute.length; i++) {
      if (attribute[i].groupId == delItem.groupId && attribute[i].attributeId == delItem.attributeId) {
        attribute.splice(i, 1);
        break
      }
    }

    groups[gi].selectedList.splice(si, 1)
    if (delItem.attributePrice) {
      good.jiaqian -= parseInt(delItem.attributePrice);

    }
    good.attributeGroups = groups;
    this.setData({
      good: good
    })
  },

})